//
//  DDDiscoverViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/3/13.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.


#import "DDDiscoverViewController.h"
#import "DDDiscoverJobCell.h"
#import "DDSearchController.h"
#import "DDWorkDetailViewController.h"
#import "DDJobsService.h"
#import "DDJobsBaseModel.h"
#import "HMSegmentedControl.h"
#import "SDCycleScrollView.h"
#import "DDNavigationBarPullView.h"
#import "DDJobfinderDetailInfo.h"

#import "DDSegementTabbarView.h"
#import "DDCommonDataModel.h"
#import <MJRefresh/MJRefresh.h>

#define kTableViewHeight    kScreenHeight  - 49 -64 -44

@interface DDDiscoverViewController () <SDCycleScrollViewDelegate, UIActionSheetDelegate>


typedef enum TableShowCommType{
    
    SeeLittleJobs,//触发逛一逛
    SeeNormalJobs
    
}TableShowType;

@property (assign, nonatomic) TableShowType tableType;
@property (nonatomic,assign) NSInteger startIndexSeeLittleJob;

@property (strong, nonatomic) DDJobsService *jobsService;
@property (strong, nonatomic) HMSegmentedControl *segmentedControl;
@property (strong, nonatomic) DDNavigationBarPullView *pullView;

@property (strong, nonatomic) DDJobfinderDetailInfo *detailInfo;
@property (strong, nonatomic) NSMutableArray *expectJobArray;

@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) NSString *titleString;
@property (strong, nonatomic) UIButton *showMenuButton;

@property (strong, nonatomic) UIView *menuView;

// 期望工作ID
@property (copy, nonatomic) NSString *expectJobId;

// 月薪 经验 学历View
@property (strong, nonatomic) DDSegementTabbarView *segmentView;
@property (strong, nonatomic) NSMutableArray *companySizeArray;
@property (strong, nonatomic) NSMutableArray *experiencesArray;
@property (strong, nonatomic) NSMutableArray *salaryArray;
// 筛选类型
@property (strong, nonatomic) NSString *filterType;
// 筛选条件ID
@property (strong, nonatomic) NSString *filterId;

@property (strong, nonatomic) UIImageView *adImageView;

//用户信息(牛人端)
@property (strong, nonatomic) DDUserInfoModel *userModel;

@property (nonatomic, strong) DDUserInfoService *userService;

@end

@implementation DDDiscoverViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.jobsService = [[DDJobsService alloc] init];
        self.expectJobArray = [[NSMutableArray alloc] init];
        self.startIndexSeeLittleJob = 0;
        
    }
    return self;
}

- (DDUserInfoService *)userService
{
    if (!_userService){
        _userService = [[DDUserInfoService alloc] init];
    }
    return _userService;
}

#pragma mark
#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpView];
    [self setUpData];
    
    [self setUpADScrollView];
    [self getMyExpectJob];
    
    [self requestRecommendJobsData];
    [self initRAC];
}

- (void) setUpData{
    
    _tableType = SeeNormalJobs;
    self.dataSourceRecommend = [[NSMutableArray alloc] init];
}

//逻辑操作
- (void)initRAC {
    
    //请求刷新
    WEAKSELF
    [[self rac_signalForSelector:@selector(viewWillAppear:)] subscribeNext:^(id x) {
        
        
        [weakSelf.rdv_tabBarController setTabBarHidden:false animated:true];
        [[DDUserInfoService sharedService]queryUserInfoWithFresh:YES callback:^(DDUserInfoModel *model) {
            weakSelf.userModel = model;
        }];
    }];
    //view hidden
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        
        if (!self.pullView.hidden && self.pullView.isShowPullView) {
            [self.pullView dismissPullView];
            self.titleLabel.attributedText = [self setTitleAttributed];
        }
    }];
    
    //筛选小尖头
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:DISSMISSACTIONSHEET object:nil] subscribeNext:^(id x) {
        
        if (weakSelf.segmentView.salaryButton.selected == YES) {
            weakSelf.segmentView.salaryButton.selected = NO;
        }
        if ( weakSelf.segmentView.experienceButton.selected == YES) {
            weakSelf.segmentView.experienceButton.selected = NO;
        }
        if (weakSelf.segmentView.eduButton.selected == YES) {
            
            weakSelf.segmentView.eduButton.selected = NO;
        }
        
    }];
    
    //获得 默认工作ID（可能由其他界面改变）
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:NOTI_CATTLE_EDIT_EXPECTJOB object:nil] subscribeNext:^(id x) {
        
        [weakSelf getMyExpectJob];
    }];
    //
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -
#pragma mark Private Methods

- (void)setUpView
{
    self.navigationItem.title = @"发现";
    self.titleString = @"选择职位";
    
    self.view.backgroundColor = COLOR_BACKGROUND_GRAY;
    self.navigationController.navigationBar.translucent = false;
    self.navigationController.navigationBar.barTintColor = COLOR_NAVIGATIONBAR;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:16]}];
    
    [self addRightButtonItemWithImage:[UIImage imageNamed:@"common_nav_search"] action:@selector(searchClick)];
    
    [self.view addSubview:self.showMenuButton];
    
    // segmentControl
    [self.view addSubview:self.segmentedControl];
    
    // 设置筛选View
    [self setSegementView];
}

- (void)setSegementView
{
    self.segmentView = [DDSegementTabbarView segementView];
    [self.view addSubview:self.segmentView];
    [self.segmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(40);
        make.left.mas_equalTo(kScreenWidth);
        
    }];
    //    self.segmentView.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, 40);
    [self.segmentView.eduButton setTitle:@"规模" forState:UIControlStateNormal];
    
    
    WEAKSELF
    
    [self.segmentView.hideButton bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.3f animations:^{
            weakSelf.segmentView.frame = CGRectMake(kScreenWidth, 0, kScreenWidth, 40);
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
    // 月薪
    [self.segmentView.salaryButton bk_addEventHandler:^(id sender) {
        
        weakSelf.segmentView.salaryButton.selected = YES;
        weakSelf.segmentView.experienceButton.selected = NO;
        weakSelf.segmentView.eduButton.selected = NO;
        
        [weakSelf showSalaryChoose];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    // 经验
    [self.segmentView.experienceButton bk_addEventHandler:^(id sender) {
        
        weakSelf.segmentView.experienceButton.selected = YES;
        weakSelf.segmentView.salaryButton.selected = NO;
        weakSelf.segmentView.eduButton.selected = NO;
        
        [weakSelf showExperienceChoose];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    // 公司规模
    [self.segmentView.eduButton bk_addEventHandler:^(id sender) {
        
        weakSelf.segmentView.eduButton.selected = YES;
        weakSelf.segmentView.salaryButton.selected = NO;
        weakSelf.segmentView.experienceButton.selected = NO;
        
        [weakSelf showCompanySizeChoose];
        
    } forControlEvents:UIControlEventTouchUpInside];
}
//Salary
- (void)showSalaryChoose
{
    WEAKSELF
    
    [[LDCheckPublicInfo shareInstance] checkoutAllSalaryJobfinder :^(NSArray<NSDictionary *> * _Nonnull data) {
        
        
        NSArray *titleArr = [self getArrFormDictArrFilterKey:@"salary_text" arrDict:data];
        NSArray *titleArrID = [self getArrFormDictArrFilterKey:@"salary_id" arrDict:data];
        
        [self showLDActionSheetView:@"薪资" labHeight:nil labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.segmentView.salaryButton.selected = NO;
            weakSelf.filterId = titleArrID[index];
            weakSelf.filterType = @"salary";
            [weakSelf requestSiftJobs];
            
        }];
        
    }];
    
}

//Experience
- (void)showExperienceChoose
{
    WEAKSELF
    
    [[LDCheckPublicInfo shareInstance] checkoutAllExperienceJobfinder:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        
        NSArray *titleArr = [self getArrFormDictArrFilterKey:@"experience_text" arrDict:data];
        NSArray *titleArrID = [self getArrFormDictArrFilterKey:@"experience_id" arrDict:data];
        
        [self showLDActionSheetView:@"经验" labHeight:nil labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.segmentView.experienceButton.selected = NO;
            weakSelf.filterId = titleArrID[index];
            weakSelf.filterType = @"experience";
            [weakSelf requestSiftJobs];
            
        }];
        
    }];
}

//CompanySize
- (void)showCompanySizeChoose
{
    WEAKSELF
    [[LDCheckPublicInfo shareInstance] checkoutCompanySizeJobfinder:^(NSArray<NSDictionary *> * _Nonnull data) {
        
        NSArray *titleArr = [self getArrFormDictArrFilterKey:@"companysize_text" arrDict:data];
        NSArray *titleArrID = [self getArrFormDictArrFilterKey:@"companysize_id" arrDict:data];
        
        [self showLDActionSheetView:@"公司规模" labHeight:nil labsTitleArr:titleArr selClosure:^(NSInteger index) {
            
            weakSelf.segmentView.eduButton.selected = NO;
            weakSelf.filterId = titleArrID[index];
            weakSelf.filterType = @"size";
            [weakSelf requestSiftJobs];
            
        }];
        
    }];
}

//
- (void)setCurrentExpectJobId
{
    
    WEAKSELF
    [self.jobsService setMyselfCurrentExpectJobId:self.expectJobId successBlock:^(id responseObject) {
        if ([weakSelf isValidateResponseData:responseObject]) {
            
            [weakSelf loadNewData];
        } else {
            
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        
        [weakSelf requestFaild];
    }];
}

/**
 *  设置广告图
 */
- (void)setUpADScrollView
{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, kScreenWidth, kScreenWidth * kDiscoverAdsScale);
    headerView.backgroundColor = COLOR_BACKGROUND;
    
    [headerView addSubview:self.adImageView];
    
    self.tableViewRecommend.tableHeaderView = headerView;
    [self.adImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.mas_equalTo(headerView).with.insets(UIEdgeInsetsMake(8, 10, 0, 10));
    }];
    
    //加入缓存机制
    WEAKSELF
    [[LDBossInfoNet sharedInstance] queryEmployerAds:^(NSArray<NSString *> * _Nonnull dictArr) {
        
        NSURL *url = [NSURL URLWithString:dictArr[1]];
        [weakSelf.adImageView sd_setImageWithURL:url];
        
    } failure:^(id  _Nonnull error) {
        
        
    }];
    
}

-(UIImageView *)adImageView {
    
    if (_adImageView == nil) {
        
        _adImageView = [[UIImageView alloc] init];
        _adImageView.layer.cornerRadius = 3;
        _adImageView.layer.masksToBounds = true;
        _adImageView.userInteractionEnabled = true;
        
        WEAKSELF
        [_adImageView bk_whenTapped:^{
            LDBaseWebViewController *vc = [[LDBaseWebViewController alloc] init];
            vc.reqUrl = @"https://www.51ledian.com";
            vc.webview.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT);
            [weakSelf.navigationController pushViewController:vc animated:true];
        }];
        
    }
    return _adImageView;
}

//搜索事件
- (void)searchClick
{
    LDFinderSearchVC *searchVC = [[LDFinderSearchVC alloc] init];
    [self.navigationController pushViewController:searchVC animated:false];
}


- (void)showMenuButtonClick:(id)button
{
    [UIView animateWithDuration:0.3f animations:^{
        
        self.segmentView.frame = CGRectMake(0, 0, kScreenWidth, 40);
    }];
}

#pragma mark
#pragma mark - TitleView

- (void)setNavgationBarTitleWithInfo:(DDJobfinderDetailInfo *)info
{
    
    self.expectJobArray = [NSMutableArray arrayWithArray:info.expectedjobs];
    
    if ([self.expectJobArray count] > 0) {
        
        DDExpectJobDetail *detail = (DDExpectJobDetail *)self.expectJobArray[0];
        self.titleString = detail.expectjobcategory_name;
        self.expectJobId = detail.expectjobid;
    }
    
    self.pullView = [[DDNavigationBarPullView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 -49)];
    
    self.pullView.hidden = YES;
    [self.view addSubview:_pullView];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    self.titleLabel.attributedText = [self setTitleAttributed];
    
    self.titleLabel.frame = CGRectMake(0, 0, 180, 30);
    self.navigationItem.titleView = self.titleLabel;
    
    
    WEAKSELF
    NSMutableArray *tempTitlesArray = [@[] mutableCopy];
    // 设置最多显示前三个
    for (int i = 0; i < [self.expectJobArray count]; i ++) {
        
        if (i == 3) {
            break;
        }
        
        DDExpectJobDetail *tempDetail = (DDExpectJobDetail *)self.expectJobArray[i];
        if (tempDetail.expectjobcategory_name) {
            [tempTitlesArray addObject:tempDetail.expectjobcategory_name];
        }
    }
    
    [tempTitlesArray addObject:@"逛一逛"];
    [tempTitlesArray addObject:@"管理期望工作"];
    
    self.pullView.titles = [NSArray arrayWithArray:tempTitlesArray];
    
    self.pullView.seletedTitleBlock = ^(NSInteger idx) {
        
        weakSelf.titleString = tempTitlesArray[idx];
        
        if (idx != tempTitlesArray.count - 1) {
            
            weakSelf.titleLabel.attributedText = [weakSelf setTitleAttributed];
        }
        
        [weakSelf updateWithTypeIdx:idx];
        
    };
    
    if (tempTitlesArray.count == 2) {
        
        [weakSelf updateWithTypeIdx:0];
        self.titleString = tempTitlesArray[0];
        self.titleLabel.attributedText = [weakSelf setTitleAttributed];
    }
    
    self.titleLabel.userInteractionEnabled = YES;
    [self.titleLabel bk_whenTapped:^{
        
        if (![weakSelf.pullView isShowPullView]) {
            
            [weakSelf.pullView showPullView];
        } else {
            
            [weakSelf.pullView dismissPullView];
        }
        weakSelf.titleLabel.attributedText = [weakSelf setTitleAttributed];
        
    }];
    
    
}

//判断逛一逛,管理期望工作
- (void)updateWithTypeIdx:(NSInteger)idx {
    
    int index = (int) idx;
    int arrcount = (int) self.expectJobArray.count;
    
    
    if (index == arrcount) {
        
        
        self.tableType = SeeLittleJobs;
        self.segmentedControl.hidden = true;
        self.showMenuButton.hidden = true;
        self.scrollView.scrollEnabled = false;
        self.segmentView.hidden = true;
        
        self.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kTableViewHeight + 44);
        self.tableViewRecommend.frame = self.scrollView.frame;
        
        self.startIndexSeeLittleJob = 0;
        [self requestALittleJobs];
        
    } else if (index == arrcount + 1) {
        
        // 管理期望工作
        LDManageMyResumeVC *vc = [[LDManageMyResumeVC alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        WEAKSELF
        [weakSelf updateWithTypeIdx:0];
        self.titleString = self.pullView.titles[0];
        self.titleLabel.attributedText = [weakSelf setTitleAttributed];
        
    } else {
        
        self.tableType = SeeNormalJobs;
        self.segmentedControl.hidden = false;
        self.showMenuButton.hidden = false;
        self.scrollView.scrollEnabled = true;
        self.segmentView.hidden = false;
        
        self.scrollView.frame = CGRectMake(0, 44, kScreenWidth, kTableViewHeight);
        self.tableViewRecommend.frame = CGRectMake(0, 0, kScreenWidth, kTableViewHeight);
        
        
        DDExpectJobDetail *detail = (DDExpectJobDetail *)self.expectJobArray[idx];
        self.expectJobId = detail.expectjobid;
        [self setCurrentExpectJobId];
        
    }
}


- (NSMutableAttributedString *)setTitleAttributed
{
    NSMutableAttributedString *titleAttributed = [[NSMutableAttributedString alloc] initWithString:self.titleString];
    [titleAttributed addAttribute:NSForegroundColorAttributeName
                            value:[UIColor whiteColor]
                            range:NSMakeRange(0,self.titleString.length)];
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    if ([self.pullView isShowPullView]) {
        textAttachment.image = [UIImage imageNamed:@"pull_up"];
    } else {
        textAttachment.image = [UIImage imageNamed:@"pull_down"];
    }
    
    textAttachment.bounds = CGRectMake(5, 2, 9, 5);
    [titleAttributed insertAttributedString:[NSAttributedString attributedStringWithAttachment:textAttachment] atIndex:self.titleString.length];
    return titleAttributed;
}


#pragma mark
#pragma mark - Data

// 获取期望工作
- (void)getMyExpectJob
{
    WEAKSELF
    [self.jobsService queryMyselfResumeSuccessBlock:^(id responseObject) {
        if ([weakSelf isValidateResponseData:responseObject]) {
            DDJobfinderDetailInfo *jobfinderInfo = [DDJobfinderDetailInfo yy_modelWithJSON:responseObject[@"data"]];
            weakSelf.detailInfo = jobfinderInfo;
            [weakSelf setNavgationBarTitleWithInfo:weakSelf.detailInfo];
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}

- (void)requestRecommendJobsData
{
    if (self.startIndexPageRecommend == 0) {
        [self.dataSourceRecommend removeAllObjects];
    }
    
    WEAKSELF
    
    NSString *page = [NSString stringWithFormat:@"%d",(int)self.startIndexPageRecommend];
    NSString *jobid = self.detailInfo.expectjobid;
    
    [self.jobsService queryRecommendJobsWithPage:page jobID:jobid successBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([weakSelf isValidateResponseData:responseObject]) {
            
            self.startIndexPageRecommend ++;
            // 请求数据成功
            DDJobsBaseModel *baseModel = [DDJobsBaseModel yy_modelWithJSON:responseObject[@"data"]];
            
            if ([baseModel.hasNextPage isEqualToString:@"0"]) {
                
                [weakSelf.tableViewRecommend.mj_footer setHidden:true];
            } else {
                [weakSelf.tableViewRecommend.mj_footer setHidden:false];
            }
            
            [weakSelf setFooterHidden:[baseModel.hasNextPage isEqualToString:@"0"]];
            
            [weakSelf.dataSourceRecommend addObjectsFromArray:baseModel.jobs];
            
            if ([weakSelf.dataSourceRecommend count] == 0) {
                
                [weakSelf showNoDataViewWithImage:nil text:STR_NODATA];
            } else {
                
                [weakSelf hideNoDataView];
            }
            
            [weakSelf endRefreshHeader];
            [weakSelf endRefreshFooter];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableViewRecommend reloadData];
            });
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}

- (void)requestHottestData
{
    if (self.startIndexPageHottest == 0) {
        [self.dataSourceHotest removeAllObjects];
    }
    [self requestJobsData:@"hottest"];
}

- (void)requestLatestData
{
    if (self.startIndexPageLatest == 0) {
        [self.dataSourceLatest removeAllObjects];
    }
    [self requestJobsData:@"latest"];
}

- (void)requestJobsData:(NSString *)order
{
    WEAKSELF
    [self.jobsService queryHotestOrLatestJobsWithPage:@"0" order:order successBlock:^(id responseObject) {
        
        [weakSelf hideLoading];
        if ([weakSelf isValidateResponseData:responseObject]) {
            // 请求成功
            DDJobsBaseModel *model = [DDJobsBaseModel yy_modelWithJSON:responseObject[@"data"]];
            
            [weakSelf setFooterHidden:[model.hasNextPage isEqualToString:@"0"]];
            
            if ([model.jobs count] == 0) {
                [weakSelf showNoDataViewWithImage:nil text:@"暂无数据"];
            } else {
                [weakSelf hideNoDataView];
            }
            
            [weakSelf endRefreshHeader];
            [weakSelf endRefreshFooter];
            
            if ([order isEqualToString:@"hottest"]) {
                self.startIndexPageHottest ++;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.dataSourceHotest addObjectsFromArray:model.jobs];
                    [weakSelf.tableViewHotest reloadData];
                });
            }
            
            if ([order isEqualToString:@"latest"]) {
                self.startIndexPageLatest ++;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.dataSourceLatest addObjectsFromArray:model.jobs];
                    [weakSelf.tableViewLatest reloadData];
                });
                
            }
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}

/**
 *  请求筛选条件的数据
 */
- (void)requestSiftJobs
{
    WEAKSELF
    
    [self.jobsService queryJobsWithJobId:self.expectJobId Filtertype:self.filterType FilterID:self.filterId page:@"0" SuccessBlock:^(id responseObject) {
        if ([weakSelf isValidateResponseData:responseObject]) {
            // 请求成功
            DDJobsBaseModel *model = [DDJobsBaseModel yy_modelWithJSON:responseObject[@"data"]];
            
            if ([model.jobs count] == 0) {
                
                [weakSelf showNoDataViewWithImage:nil text:@"暂无数据"];
            } else {
                [weakSelf hideNoDataView];
            }
            
            NSInteger page = (self.scrollView.contentOffset.x + self.scrollView.frame.size.width/2)/ self.scrollView.frame.size.width;
            
            if (page == 0) {
                [weakSelf.dataSourceRecommend removeAllObjects];
                [weakSelf.dataSourceRecommend addObjectsFromArray:model.jobs];
                
            } else if (page == 1) {
                [weakSelf.dataSourceHotest removeAllObjects];
                [weakSelf.dataSourceHotest addObjectsFromArray:model.jobs];
            } else if (page == 2) {
                // 最新
                [weakSelf.dataSourceLatest removeAllObjects];
                [weakSelf.dataSourceLatest addObjectsFromArray:model.jobs];
            }
            if ([weakSelf getCurrentShowTableView]) {
                [[weakSelf getCurrentShowTableView] reloadData];
            }
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}

- (UITableView *)getCurrentShowTableView
{
    UITableView *tableView = nil;
    NSInteger page = (self.scrollView.contentOffset.x + self.scrollView.frame.size.width/2)/ self.scrollView.frame.size.width;
    
    if (page == 0) {
        tableView = self.tableViewRecommend;
        
    } else if (page == 1) {
        tableView = self.tableViewHotest;
    } else if (page == 2) {
        // 最新
        tableView = self.tableViewLatest;
    }
    
    return tableView;
}

//牛人端逛一逛
- (void) requestALittleJobs {
    
    WEAKSELF
    [[LDUserInfoNet sharedInstance] jobfinderSeeALittleJob:self.startIndexSeeLittleJob succ:^(NSDictionary<NSString *,id> * _Nonnull dictArr) {
        
        // 请求数据成功
        if (self.startIndexSeeLittleJob == 0) {
            [self.dataSourceRecommend removeAllObjects];
        }
        
        self.startIndexSeeLittleJob ++;
        
        DDJobsBaseModel *baseModel = [DDJobsBaseModel yy_modelWithJSON:dictArr];
        [weakSelf setFooterHidden:false];
        [weakSelf.dataSourceRecommend addObjectsFromArray:baseModel.jobs];
        
        if ([weakSelf.dataSourceRecommend count] == 0) {
            
            [weakSelf showNoDataViewWithImage:nil text:STR_NODATA];
        } else {
            
            [weakSelf hideNoDataView];
        }
        
        [weakSelf endRefreshHeader];
        [weakSelf endRefreshFooter];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [weakSelf.tableViewRecommend reloadData];
        });
        
    } fail:^(id  _Nonnull err) {
        
    }];
}

#pragma mark
#pragma mark - Header & Footer Refresh

/**
 *  下拉刷新数据
 */
- (void)loadNewData
{
    NSInteger page = (self.scrollView.contentOffset.x + self.scrollView.frame.size.width/2)/ self.scrollView.frame.size.width;
    
    
    if (self.tableType == SeeLittleJobs) {
        
        self.startIndexSeeLittleJob = 0;
        [self requestALittleJobs];
        
    } else {
        
        switch (page) {
                
            case 0:
                // 推荐
                self.startIndexPageRecommend = 0;
                [self requestRecommendJobsData];
                break;
            case 1:
                
                // 最热
                self.startIndexPageHottest = 0;
                [self requestHottestData];
                break;
            case 2:
                // 最新
                self.startIndexPageLatest = 0;
                [self requestLatestData];
                break;
                
            default:
                break;
        }
    }
}

/**
 *  上拉加载更多数据
 */
- (void)loadMoreData
{
    NSInteger page = (self.scrollView.contentOffset.x + self.scrollView.frame.size.width/2)/ self.scrollView.frame.size.width;
    
    
    if (self.tableType == SeeLittleJobs) {
        
        // 逛一逛
        //        self.startIndexSeeLittleJob = 0;
        [self popRemaind];
        
    } else {
        
        switch (page) {
                
            case 0:
                // 推荐
                //                self.startIndexPageRecommend = 0;
                [self requestRecommendJobsData];
                
                break;
            case 1:
                
                // 最热
                //                self.startIndexPageHottest = 0;
                [self requestHottestData];
                break;
            case 2:
                // 最新
                //                self.startIndexPageLatest = 0;
                [self requestLatestData];
                break;
                
            default:
                break;
        }
    }
    
    //
    //    if (page == 0) {
    //        // 推荐
    //        [self requestRecommendJobsData];
    //    } else if (page == 1) {
    //        // 最热
    //        [self requestHottestData];
    //    } else if (page == 2) {
    //        // 最新
    //        [self requestLatestData];
    //    }
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableViewRecommend) {
        return [self.dataSourceRecommend count];
    } else if (tableView == self.tableViewHotest) {
        return [self.dataSourceHotest count];
    } else if (tableView == self.tableViewLatest) {
        return [self.dataSourceLatest count];
    } else {
        
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 182;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDDiscoverJobCell *cell;
    if (tableView == self.tableViewRecommend) {
        
        cell = (DDDiscoverJobCell *)[tableView dequeueReusableCellWithIdentifier:DDDiscoverJobCellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DDDiscoverJobCell" owner:self options:nil] lastObject];
        }
        
        if ([self.dataSourceRecommend count] > indexPath.row) {
            
            [cell updateViewWithData:(DDJobsDetail *)self.dataSourceRecommend[indexPath.row]];
        }
        
    } else if (tableView == self.tableViewHotest) {
        
        cell = (DDDiscoverJobCell *)[tableView dequeueReusableCellWithIdentifier:DDDiscoverJobCellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DDDiscoverJobCell" owner:self options:nil] lastObject];
        }
        
        if ([self.dataSourceHotest count] > indexPath.row) {
            [cell updateViewWithData:(DDJobsDetail *)self.dataSourceHotest[indexPath.row]];
        }
        
    } else if (tableView == self.tableViewLatest) {
        
        cell = (DDDiscoverJobCell *)[tableView dequeueReusableCellWithIdentifier:DDDiscoverJobCellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DDDiscoverJobCell" owner:self options:nil] lastObject];
        }
        
        if ([self.dataSourceLatest count] > indexPath.row) {
            [cell updateViewWithData:(DDJobsDetail *)self.dataSourceLatest[indexPath.row]];
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


//
-(RecommendJobTableCell *) getCellFromTypeCategory:(UITableView *) tableView indexPath:(NSIndexPath *)indexPath {
    
    RecommendJobTableCell *cell;
    cell = (RecommendJobTableCell *)[tableView dequeueReusableCellWithIdentifier:@"DDRecBossDiscoverCellIdentifier"];
    
    //    if (cell == nil) {
    //
    //        cell = [[RecommendJobTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DDRecBossDiscoverCellIdentifier"];
    //    }
    //
    //    if (tableView == self.tableViewRecommend) {
    //
    //        DDJobsDetail *models = (DDJobsDetail *)self.dataSourceRecommend[indexPath.row];
    ////        cell.ddModels = models;
    //
    //    } else if (tableView == self.tableViewHotest) {
    //
    //        DDJobsDetail *models = (DDJobsDetail *)self.dataSourceHotest[indexPath.row];
    //        cell.DDModels = models;
    //
    //    } else if (tableView == self.tableViewLatest) {
    //
    //        DDJobsDetail *models = (DDJobsDetail *)self.dataSourceLatest[indexPath.row];
    //        cell.DDModels = models;
    //
    //    }
    
    return cell;
}


#pragma mark -
#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [[DDVerifyInfoManger alloc] getDataVerifyClosure:^(BOOL isAcc) {
        
        
        if (isAcc == true) {
            
            DDJobsDetail *detail;
            
            if (tableView == self.tableViewRecommend) {
                detail = (DDJobsDetail *)self.dataSourceRecommend[indexPath.row];
            } else if (tableView == self.tableViewHotest) {
                detail = (DDJobsDetail *)self.dataSourceHotest[indexPath.row];
            } else {
                detail = (DDJobsDetail *)self.dataSourceLatest[indexPath.row];
            }
            
            
            DDWorkDetailViewController *workVC = [[DDWorkDetailViewController alloc] init];
            workVC.title = detail.jobtitle;
            workVC.jobDetail = detail;
            workVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:workVC animated:YES];
            
            
        } else {
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                WEAKSELF
                [self showLDAlertView:@"简历信息未完善\n是否完善？" sure:^{
                    LDMyResumeViewControllerInOne *vc = [[LDMyResumeViewControllerInOne alloc]init];
                    [weakSelf.navigationController pushViewController:vc animated:true];
                } cancel:nil];
            }];
        }
    }];
    // 权限设置
//    if (!self.userModel.name||!self.userModel.sex||!self.userModel.experience) {
//
//        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//            WEAKSELF
//            [self showLDAlertView:@"个人信息未完善，前去完善" sure:^{
//                LDMyResumeViewControllerInOne *vc = [[LDMyResumeViewControllerInOne alloc]init];
//                [weakSelf.navigationController pushViewController:vc animated:true];
//            } cancel:nil];
//        }];
//        
//        
//        
//    }  else  {
//        
//        if (self.userModel.expectedjobs.count == 0) {
//            
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                WEAKSELF
//                [self showLDAlertView:@"请先填写期望职位" sure:^{
//                    LDManageMyResumeVC *vc = [[LDManageMyResumeVC alloc]init];
//                    [weakSelf.navigationController pushViewController:vc animated:true];
//                } cancel:nil];
//            }];
//        }else{
//            DDJobsDetail *detail;
//            
//            if (tableView == self.tableViewRecommend) {
//                detail = (DDJobsDetail *)self.dataSourceRecommend[indexPath.row];
//            } else if (tableView == self.tableViewHotest) {
//                detail = (DDJobsDetail *)self.dataSourceHotest[indexPath.row];
//            } else {
//                detail = (DDJobsDetail *)self.dataSourceLatest[indexPath.row];
//            }
//            
//            
//            DDWorkDetailViewController *workVC = [[DDWorkDetailViewController alloc] init];
//            workVC.title = detail.jobtitle;
//            workVC.jobDetail = detail;
//            workVC.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:workVC animated:YES];
//        }
//    }
}

#pragma mark
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (![scrollView isKindOfClass:[UITableView class]]) {
        NSInteger page = (scrollView.contentOffset.x + scrollView.frame.size.width/2)/ scrollView.frame.size.width;
        
        [self.segmentedControl setSelectedSegmentIndex:page animated:YES];
        
        [self loadNewData];
    }
}

#pragma mark
#pragma mark - HMSegmentControlDelegate

- (void)discoverSegmentedControlChangedValue:(HMSegmentedControl *)segement
{
    //    [self loadNewData];
    
    //    NSLog(@"discoverSegmentedControlChangedValue————————————");
}

#pragma mark
#pragma mark - Getters and Setters

- (UIButton *)showMenuButton
{
    if (!_showMenuButton) {
        _showMenuButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_showMenuButton setImage:[UIImage imageNamed:@"button_job_switch"] forState:UIControlStateNormal];
        _showMenuButton.backgroundColor = [UIColor whiteColor];
        _showMenuButton.frame = CGRectMake(SCREEN_WIDTH - 50, 0, 50, 40);
        _showMenuButton.layer.borderColor = COLOR_BORDER_LIGHT_GRAY.CGColor;
        _showMenuButton.layer.borderWidth = 0.5;
        [_showMenuButton addTarget:self action:@selector(showMenuButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _showMenuButton;
}

- (HMSegmentedControl *)segmentedControl
{
    if (!_segmentedControl) {
        _segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"推荐", @"最热", @"最新"]];
        _segmentedControl.backgroundColor = [UIColor whiteColor];
        _segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:COLOR_FONT_DARK_GRAY,NSFontAttributeName:[UIFont systemFontOfSize:15]};
        _segmentedControl.selectionIndicatorHeight = 2.f;
        _segmentedControl.selectionIndicatorColor = COLOR_NAVIGATIONBAR;
        _segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
        WEAKSELF
        [_segmentedControl setIndexChangeBlock:^(NSInteger index) {
            //            NSLog(@"setIndexChangeBlock————————————");
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.scrollView setContentOffset:CGPointMake(index * SCREEN_WIDTH, 0) animated:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf loadNewData];
                });
                
            });
            
        }];
        _segmentedControl.layer.shadowColor = COLOR_BORDER_GRAY.CGColor;
        _segmentedControl.layer.shadowOffset = CGSizeMake(0.0f, 3.0f);
        _segmentedControl.frame = CGRectMake(0, 0, SCREEN_WIDTH - 50, 40);
        [_segmentedControl addTarget:self action:@selector(discoverSegmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentedControl;
}

- (UILabel *)titleLabel
{
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = [UIColor whiteColor];
        
        _titleLabel.frame = CGRectMake(0, 0, 180, 30);
    }
    
    return _titleLabel;
}

// 逛一逛提示弹窗
- (void)popRemaind
{
    [self endRefreshFooter];
    
    // 权限设置
    [[DDVerifyInfoManger alloc] getDataVerifyClosure:^(BOOL isAcc) {
        
        if (isAcc == true) {
            
            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            
            [self showLDAlertView:@"逛一逛最多显示20条数据"];
            }];
            
        } else {
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                WEAKSELF
                [self showLDAlertView:@"简历信息未完善\n是否完善？" sure:^{
                    LDMyResumeViewControllerInOne *vc = [[LDMyResumeViewControllerInOne alloc]init];
                    [weakSelf.navigationController pushViewController:vc animated:true];
                } cancel:nil];
            }];
        }
    }];
//    if (!self.userModel.name||!self.userModel.sex||!self.userModel.experience) {
//        
//        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//            WEAKSELF
//            [self showLDAlertView:@"个人信息未完善，前去完善" sure:^{
//                LDMyResumeViewControllerInOne *vc = [[LDMyResumeViewControllerInOne alloc]init];
//                [weakSelf.navigationController pushViewController:vc animated:true];
//            } cancel:nil];
//        }];
//        
//        
//    }else{
//        
//        if (self.userModel.expectedjobs.count == 0) {
//            
//            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//                WEAKSELF
//                [self showLDAlertView:@"请先填写期望职位" sure:^{
//                    LDManageMyResumeVC *vc = [[LDManageMyResumeVC alloc]init];
//                    [weakSelf.navigationController pushViewController:vc animated:true];
//                } cancel:nil];
//            }];
//        }else{
//            
//            [[NSOperationQueue mainQueue]addOperationWithBlock:^{
//                
//                [self showLDAlertView:@"逛一逛最多显示20条数据"];
//            }];
//        }
//    }
}

@end